package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 银行账户 服务实现类
 * </p>
 *
 * @author mr.zhao
 * @since 2025-07-02
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {


	/**
	 * 新增银行账号信息
	 *
	 * @param dto
	 */
	@Override
	public void addBankAccount(BankAccountUpsertReqDTO dto) {
		//1. 参数校验
		if (dto == null){
			throw new ForbiddenOperationException("参数非法");
		}

		//2. 根据银行卡号判断是否已经添加过
		BankAccount one = this.lambdaQuery().eq(BankAccount::getAccount, dto.getAccount())
				.eq(BankAccount::getBankName,dto.getBankName())
				.one();
		if (one != null){
			boolean result = this.removeById(one.getId());
			if (!result){
				throw new DBException("删除失败");
			}
		}

		//3. 添加
		BankAccount bankAccount = BeanUtil.toBean(dto, BankAccount.class);
		Long userId = UserContext.currentUserId();
		bankAccount.setId(userId);
		boolean result = this.save(bankAccount);
		if (!result){
			throw new DBException("新增或更新失败");
		}

	}

	/**
	 * 获取当前用户银行账号
	 *
	 * @return
	 */
	@Override
	public BankAccountResDTO getBankAccount() {
		Long userId = UserContext.currentUserId();
		BankAccount bankAccount = this.lambdaQuery().eq(BankAccount::getId, userId).one();
		BankAccountResDTO bankAccountResDTO = BeanUtil.toBean(bankAccount, BankAccountResDTO.class);
		return bankAccountResDTO;
	}
}
